﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;

namespace CopySniffer.UI.Core.FileLoad
{
    // TODO: remove this class and its dependencies to a separate assembly,
    // so the app itself does not depend on word being installed.
    public class WordFileLoader : IFileLoader
    {
        private readonly string[] supportedExtensions = 
        {
            "doc",
            "docx"
        };

        #region IFileLoader Members

        public IEnumerable<string> SupportedExtensions
        {
            get { return supportedExtensions; }
        }

        public string TypeAlias
        {
            get { return "Microsoft Word Document"; }
        }

        public string LoadFile(string fileName)
        {
            string result = null;
            Microsoft.Office.Interop.Word.Application wap = null;
            Microsoft.Office.Interop.Word.Document wdoc = null;
            object missing = System.Reflection.Missing.Value;
            object objFalse = false;
            object objTrue = true;
            object objFileName = fileName;
            try
            {
                wap = new Microsoft.Office.Interop.Word.ApplicationClass();
                wdoc = wap.Documents.Open(
                    ref objFileName,
                    ref objFalse,
                    ref objTrue,
                    ref objFalse,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref objTrue,
                    ref missing,
                    ref missing,
                    ref missing,
                    ref missing);  //16 parameters!
                result = wdoc.Content.Text;

                // It seems Word likes adding a LF char at the end of documents,
                // even if the user did not input it. In case it happened, this
                // removes the additional char.
                if ((result != null) && (result.EndsWith("\r")))
                {
                    result = result.Remove(result.Length - 1);
                }
            }
            finally
            {
                if (wdoc != null)
                {
                    ((_Document)wdoc).Close(ref objFalse, ref missing, ref missing);
                }

                if (wap != null)
                {
                    ((_Application)wap).Quit(ref objFalse, ref missing, ref missing);
                }
            }
            return result;
        }

        #endregion
    }
}
